package com.uum.admin.component;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.uum.admin.pojo.entity.SysWebVisit;
import com.uum.admin.service.SysWebVisitService;
import com.uum.common.core.constant.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 定时任务默认是阻塞的(TaskSchedulingAutoConfiguration类中的TaskSchedulingProperties类下线程池数量size = 1)
 * 可以通过以下3种方法调优，该业务线程为1也足够了
 * 1、可以以异步编排的方式，自己提交到线程池
 *       CompletableFuture.runAsync(() -> {
 *             xxxService.hello();
 *         },executor);
 * 2、通过设置定时任务线程池、spring.task.scheduling.pool.size = ?
 * 3、让定时任务异步执行
 *    异步任务（TaskExecutionAutoConfiguration，默认线程池大小8 coreSize = 8;）
 *    开启异步执行@EnableAsync
 *    在方法上@Async
 *
 */
@Component
public class ScheduledTasks {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SysWebVisitService webVisitService;


    /**
     * 每天凌晨1点,将前天的web端访问记录保存到数据库
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void saveWebPVInDB() {
        //获取昨天的key
        String yesterday = DateUtil.formatDate(DateUtil.yesterday());
        String key = RedisConstants.WEB_PV + yesterday;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            Map<String,Integer>  map = redisTemplate.opsForHash().entries(key);
            List<SysWebVisit> saveList = new ArrayList<>();
            for (String k : map.keySet()) {
                SysWebVisit webVisit = new SysWebVisit();
                webVisit.setIp(k);
                webVisit.setNumber(map.get(k));
                webVisit.setTime(LocalDateTimeUtil.parseDate(DateUtil.today()));
                saveList.add(webVisit);
            }
            //保存到数据库
            boolean saveBatch = webVisitService.saveBatch(saveList);
            if (saveBatch) {
                //删除昨天的key
                redisTemplate.delete(key);
            }
        }
    }
}
